"use client";
import "./index.scss";
import React, { useEffect, useState, useMemo } from "react";
import { Switch, Input, Button, message, Segmented, Select } from "antd";
import { ConfigType } from "../type";
import Upload from "./Upload/page";
import PeopleItem from "./PeopleItem/page";
import useStore from "@/app/store/is_config";
const { TextArea } = Input;
import {
  people_stop,
  people_start,
  getJson,
  writeDocument,
  get_token,
} from "@/app/api/index";
import { PeoplePositionsOptions, PeopleFastOptions, PeopleData } from "../tool";

interface PeopleProps {
  setDate: (value: number) => void;
  setLoading?: (value: boolean) => void;
}

const ManagePeople: React.FC<PeopleProps> = ({ setDate, setLoading }) => {
  // 选中的数字人
  const [selected, setSelected] = useState<any>({ id: -1 });
  // 是否开启克隆
  const [CloneFlag, setCloneFlag] = useState<boolean>(false);
  // 克隆文本
  const [clonetxt, setclonetxt] = useState<string>("");
  // 数字人初始位置
  const [people_position, setpeople_position] = useState<any>("");
  // 数字人语速
  const [people_tts_speed_factor, setpeople_tts_speed_factor] =
    useState<any>(1);
  // 克隆文件路径
  const [FilePath, setFilePath] = useState<string>("");
  // 配置
  const { is_txt, setis_txt, is_captions, setis_captions } = useStore();

  // 数字人配置
  const [config, setConfig] = useState<ConfigType>({
    Config_Trigger: [],
    Config_Label: [],
    Config_Default: "",
  });

  useEffect(() => {
    getJson().then((res) => {
      setConfig(res.data);
      setpeople_position(res.data.Config_Default);
    });
  }, []);
  // 启动/修改
  const save = async (txt?: string) => {
    try {
      if (selected.id === -1) {
        message.error("请选择数字人");
        return;
      }
      const StartData = {
        avatar_id: selected.avatar_id,
        tts_speed_factor: people_tts_speed_factor,
        ref_file: selected.ref_file,
        ref_text: selected.txt,
      };

      if (CloneFlag) {
        if (!FilePath || !clonetxt) {
          message.error(
            `${!FilePath ? "请上传音频文件" : "请输入音频所对应的文本"}`
          );
          return;
        }
        StartData.ref_file = FilePath;
        StartData.ref_text = clonetxt;
      }
      await writeDocument("config.json", people_position, "position");
      await people_stop();
      setLoading?.(true);
      setTimeout(async () => {
        await people_start(StartData);
        message.success(txt);
        setDate(50);
      }, 1000);
      console.log(StartData);
    } catch (err) {
      message.error("服务器错误");
      console.log(err);
    }
  };

  const defaultValue = useMemo(() => people_position, [people_position]);

  return (
    <div className="manage_people">
      <PeopleItem label="数字人人物：">
        <div className="people_img">
          {PeopleData.map((item) => (
            <div
              key={item.id}
              className={`people_item ${
                selected.id === item.id ? "selected" : ""
              }`}
              onClick={() => setSelected(item)}
            >
              <img src={item.url} alt="" />
            </div>
          ))}
        </div>
      </PeopleItem>

      <PeopleItem
        label={
          <>
            数字人语速：
            <Segmented
              options={PeopleFastOptions}
              defaultValue={people_tts_speed_factor}
              onChange={(value) => setpeople_tts_speed_factor(value)}
            />
          </>
        }
      >
        <></>
      </PeopleItem>

      <PeopleItem
        label={
          <>
            数字人起始位置：
            {defaultValue && (
              <Segmented
                options={PeoplePositionsOptions}
                defaultValue={defaultValue}
                onChange={(value) => {
                  setpeople_position(value);
                }}
              />
            )}
          </>
        }
      >
        <></>
      </PeopleItem>

      <PeopleItem
        label={
          <>
            是否开启文本对话：
            <Switch value={is_txt} onChange={() => setis_txt(!is_txt)} />
          </>
        }
      ></PeopleItem>

      <PeopleItem
        label={
          <>
            是否开启字幕：
            <Switch
              value={is_captions}
              onChange={() => setis_captions(!is_captions)}
            />
          </>
        }
      ></PeopleItem>

      <PeopleItem
        label={
          <>
            数字人声音克隆：
            <Switch
              value={CloneFlag}
              onChange={() => setCloneFlag(!CloneFlag)}
            />
          </>
        }
      >
        {CloneFlag && (
          <div className="module">
            <span style={{ color: "red" }}>
              *注意：
              <br />
              1. 上传音频中的音频语音必须和音频文本输入的一致，否则会无法识别
              <br />
              2. 音频时长不能超过10秒
            </span>
            <div className="title">
              上传音频：
              <Upload
                FilePath={(url) => {
                  setFilePath(url);
                }}
              />
            </div>
            <div className="title max top">
              音频文本：
              <TextArea
                showCount
                maxLength={200}
                onChange={(e) => setclonetxt(e.target.value)}
                placeholder="请输入克隆文本"
                rows={4}
                value={clonetxt}
                style={{ width: "50%", resize: "none", fontWeight: "400" }}
              />
            </div>
          </div>
        )}
      </PeopleItem>

      <div className="footer">
        <Button onClick={() => save("操作成功")}>(修改/启动)数字人</Button>
        <Button
          onClick={() => {
            setDate(3);
            people_stop();
          }}
        >
          关闭数字人
        </Button>
      </div>
    </div>
  );
};

export default ManagePeople;
